<?php

namespace app\selladmin\controller;

use app\selladmin\controller\CommonController;
use app\selladmin\model\Selladmin;
use think\Db;
use think\Validate;
use app\util\File;
use think\Request;
use app\selladmin\model\Sellrole;

class AdminController extends CommonController {
    /*
     * 管理员列表 
     * author xfwed
     * date 2019.01.17
     */

    public function AdminList() {
        $admin_name = input('param.admin_name');
        $admin_note = input('param.admin_note');
        $code = input('param.code');
        $adminid = input('param.adminid');
        $selladmin=Selladmin::where('level','=',2)->where('status','=',1)->select();
        
        if($admin_name){
            $where['admin_name']=$admin_name;
            $query['admin_name'] = $admin_name;
        }
        
        if($admin_note){
            $where['admin_note']=array('like','%'.$admin_note.'%');
            $query['admin_note'] = $admin_note;
        }
        
        if($code){
            $where['code']=$code;
            $query['code'] = $code;
        }
        
        $admin = new Selladmin();
        $id = session('S_ID');
        $row = Selladmin::where('id','=',$id)->field('id,level')->find();
        $level = $row['level'];
        if($level==1){
            $where['level'] =['in','2,3'];
            if($adminid){
                $where['pid'] = $adminid;
                $query['adminid'] = $adminid;
            }
        }elseif ($level == 2) {
            $where['pid'] = $id;
        }elseif ($level == 0) {
            if($adminid){
                $where['pid'] = $adminid;
                $query['adminid'] = $adminid;
            }
        }
        $where = isset($where)?$where:[];
        $query = isset($query)?$query:[];
        $adminList = Selladmin::order("id asc")
                //->where('status','=',1)
                ->where($where)
                ->paginate(12)
                ->appends($query);
        
        return view('adminlist', [
            'AdminList' => $adminList,
            'admin_name' => $admin_name,
            'admin_note' => $admin_note,
            'code' => $code,
            'selladmin' => $selladmin,
            'adminid' => $adminid,
        ]);
    }

    /*
     * 添加管理员
     * author xfwed
     * date 2019.01.17
     */

    public function AddAdmin() {
        if (!$_POST) {
            $id = session("S_ID");
            $row = Selladmin::where('id','=',  $id)->field('level')->find();
            if($row['level'] == Selladmin::LEVEL_0){
                $selladmin=Selladmin::where('level','in',[Selladmin::LEVEL_1,Selladmin::LEVEL_2])
                        ->field('id,admin_note')
                        ->select();
            }elseif ($row['level'] == Selladmin::LEVEL_1) {
                $selladmin=Selladmin::where('level','=',Selladmin::LEVEL_1)
                        ->field('id,admin_note')
                        ->select();
            }elseif ($row['level'] == Selladmin::LEVEL_2) {
                $selladmin=Selladmin::where('id','=',  $id)
                        ->field('id,admin_note')
                        ->select();
            }
            return view('addadmin', ['selladmin'=>$selladmin,'level'=>$row['level']]);
        } else {
            $rule = [
                'admin_name' => 'require',
                'admin_note' => 'require',
                'admin_pwd' => 'require|min:6',
                'adminname' => 'require',
            ];
            $msg = [
                'admin_name.require' => '账号必须',
                'admin_note.require' => '名称必须',
                'admin_pwd.require' => '密码必须',
                'admin_pwd.min' => '密码最少6位',
                'adminname.require' => '请输入你的密码',
            ];
            $all = input('post.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                $this->error($error);
            }
            //验证添加者身份
            $id = session('S_ID');
            $adminfind = Selladmin::where('id=' . $id)->find();
            if ($adminfind['admin_pwd'] != md5($all['adminname'])) {
                $this->error('你的密码错误，添加失败');
            }
            $adminname = Selladmin::where("admin_name='" . $all['admin_name'] . "'")->find();
            if ($adminname) {
                $this->error('该账号已经添加');
            }
            $first_name= isset($all['first_name'])?$all['first_name']:'';
            if($first_name){
                $firstname = Selladmin::where("first_name",'=',$first_name)->find();
                if($firstname){
                    $this->error('组代码已经占用');
                }
            }
            $pid = $all['pid'];
            if($pid!=0){
                $adminname = Selladmin::where("id",'=',$pid)->find();
                $pfirstname= $adminname['first_name'];
                $level = $adminname['level'] +  1;
            }  else {
                $level = 0;
            }
            
            //上传头像
            $uploadFile = request()->file('photo');
            if ($uploadFile) {
                //验证图片
                $file = new File();
                if (!$file->checkImg($uploadFile)) {
                    $error = $file->getError();
                    $this->error($error);
                }
            } else {
                $this->error('头像必须');
            }
            $photo = $file->uploadImage($uploadFile, 'selladmin/');
            $mode = config('appconfig.app_production');
            if ($mode) {
                $publicFolder = 'kkmimg';
            } else {
                $publicFolder = 'testkkmimg';
            }
            $realPhoto = $file->getImageRealPath($photo);
            $curlPhoto = $file->curlUploadImage($publicFolder, pathinfo($photo, PATHINFO_DIRNAME), false, $realPhoto);
            if (!$curlPhoto) {
                $this->error('头像上传失败');
            }
            if($level==3){
                //获取员工唯一码 $pfirstname
                $code=Selladmin::generateStaffCode($pfirstname);
                $first_name = $pfirstname;
            }  else {
                $code = '';
            }
            $data['code'] = $code;
            $data['pid'] = $pid;
            $data['level'] = $level;
            $data['first_name'] = $first_name;
            $data['admin_name'] = $all['admin_name'];
            $data['admin_note'] = $all['admin_note'];
            $data['admin_pwd'] = md5($all['admin_pwd']);
            $data['status'] = 1;
            $data['last_time'] = time();
            $data['login_ip'] = Request::instance()->ip(); //登陆ip
            $data['photo'] = $photo;
            $data['add_time'] = time();
            $add = Db::name('selladmin')->insert($data);
            if ($add) {
                $this->success('添加成功', url('selladmin/Admin/AdminList', '', false));
            } else {
                $this->error('添加失败');
            }
        }
    }

    /*
     * 编辑管理员
     * author xfwed
     * date 2019.01.17 
     */

    public function AdminEdit() {
        $id = input('param.id');
        $adminFied = Selladmin::where('id=' . $id)->find();
        if (!$_POST) {
            $id = session("S_ID");
            $row = Selladmin::where('id','=',  $id)->field('level')->find();
            if($row['level'] == Selladmin::LEVEL_0){
                $selladmin=Selladmin::where('level','in',[Selladmin::LEVEL_1,Selladmin::LEVEL_2])
                        ->field('id,admin_note')
                        ->select();
            }elseif ($row['level'] == Selladmin::LEVEL_1) {
                $selladmin=Selladmin::where('level','=',Selladmin::LEVEL_1)
                        ->field('id,admin_note')
                        ->select();
            }elseif ($row['level'] == Selladmin::LEVEL_2) {
                $selladmin=Selladmin::where('id','=',  $id)
                        ->field('id,admin_note')
                        ->select();
            }
            return view('adminedit', ['admin' => $adminFied,'selladmin'=>$selladmin,'level'=>$row['level']]);
        } else {
            $rule = [
                'admin_name' => 'require',
                'admin_note' => 'require',
                'admin_pwd' => 'require|min:6',
                'adminname' => 'require',
            ];
            $msg = [
                'admin_name.require' => '账号必须',
                'admin_note.require' => '名称必须',
                'admin_pwd.require' => '密码必须',
                'admin_pwd.min' => '密码最少6位',
                'adminname.require' => '请输入你的密码',
            ];
            $all = input('post.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                $this->error($error);
            }
            //验证添加者身份
            $addid = session('S_ID');
            $adminfind = Selladmin::where('id=' . $addid)->find();
            if ($adminfind['admin_pwd'] != md5($all['adminname'])) {
                $this->error('你的密码错误，修改失败');
            }
            $pid = $all['pid'];
            if($pid!=0){
                $adminname = Selladmin::where("id",'=',$pid)->find();
                $pfirstname= $adminname['first_name'];
                $level = $adminname['level'] +  1;
            }  else {
                $level = 0;
            }

            //上传头像图
            $uploadFile = request()->file('photo');
            if ($uploadFile) {
                //验证图片
                $file = new File();
                if (!$file->checkImg($uploadFile)) {
                    $error = $file->getError();
                    $this->error($error);
                } else {
                    $photo = $file->uploadImage($uploadFile, 'selladmin/');
                    $mode = config('appconfig.app_production');
                    if ($mode) {
                        $publicFolder = 'kkmimg';
                    } else {
                        $publicFolder = 'testkkmimg';
                    }
                    $realPhoto = $file->getImageRealPath($photo);
                    $curlPhoto = $file->curlUploadImage($publicFolder, pathinfo($photo, PATHINFO_DIRNAME), false, $realPhoto);
                    if (!$curlPhoto) {
                        $this->error('头像上传失败');
                    } else {
                        if ($adminFied['photo']) {  
                            $file->curlDeleteImage($publicFolder, $adminFied['photo']);//删除头像
                        }
                    }
                }
            } else {
                $photo = $adminFied['photo'];
            }
            if($level==3){
                //获取员工唯一码 $pfirstname
                $code=Selladmin::generateStaffCode($pfirstname);
            }  else {
                $code = '';
            }
            $data['code'] = $code;
            $data['pid'] = $pid;
            $data['level'] = $level;
            $data['admin_name'] = $all['admin_name'];
            $data['admin_note'] = $all['admin_note'];
            $data['admin_pwd'] = md5($all['admin_pwd']);
            $data['status'] = 1;
            $data['last_time'] = time();
            $data['login_ip'] = Request::instance()->ip(); //登陆ip
            $data['photo'] = $photo;
            $save = Selladmin::where("id=" . $id)->update($data);
            if ($save) {
                $this->success('修改成功', url('selladmin/Admin/AdminList', '', false));
            } else {
                $this->success('修改失败');
            }
        }
    }

    /*
     * 改变状态
     * author xfwed
     * date 2017.08.22 
     */

    public function AdminStatus() {
        $id = input('param.id');
        $status = input('param.status');
        $data['status'] = $status;
        $save = Selladmin::where("id=" . $id)->update($data);
        if ($save) {
            $this->success('修改成功', url('selladmin/Admin/AdminList', '', false));
        } else {
            $this->success('修改失败');
        }
    }

    /*
     * 权限管理
     * author xfwed
     * date 2019.01.17
     */

    public function role() {
        $id = input('param.id');
        $adminFied = Selladmin::where('id=' . $id)->find();
        $role = $adminFied['role'];
        $roledata = Sellrole::where('pid', '=', 0)->select();
        for ($i = 0; $i < count($roledata); $i++) {
            $returndata[$i]['text'] = $roledata[$i]['name'];
            $returndata[$i]['tags'][0] = $roledata[$i]['id'];
            if (in_array($roledata[$i]['id'], explode(",", $role))) {
                $returndata[$i]['state']['checked'] = true;
            } else {
                $returndata[$i]['state']['checked'] = false;
            }
            $pdata = Sellrole::where('pid', '=', $roledata[$i]['id'])->select();
            
            $nodes = [];
            for ($j = 0; $j < count($pdata); $j++) {
                $nodes[$j]['text'] = $pdata[$j]['name'];
                $nodes[$j]['tags'][0] = $pdata[$j]['id'];
                if (in_array($pdata[$j]['id'], explode(",", $role))) {
                    $nodes[$j]['state']['checked'] = true;
                } else {
                    $nodes[$j]['state']['checked'] = false;
                }
            }
            $nodes = isset($nodes) ? $nodes : [];
            if ($nodes) {
                $returndata[$i]['nodes'] = $nodes;
            }
        }
        
        $returndata = json_encode($returndata);
        if (!$_POST) {
            return view('role', ['role' => $role, 'id' => $id, 'returndata' => $returndata]);
        } else {
            $role = input('post.role');
            $data['role'] = $role;
            $save = Selladmin::where("id=" . $id)->update($data);
            if ($save) {
                $this->success('修改成功,重新登录以后生效', url('Admin/AdminList', '', false));
            } else {
                $this->success('修改失败');
            }
        }
    }

}
